package com.jd.jdoss.config;

import com.jd.jdoss.domain.utils.WebUtil;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

@Configuration
public class MVCConfig extends WebMvcConfigurerAdapter {
    @Resource
    private RouteConfig routeConfig;

    @Bean
    MyHandlerInterceptor localInterceptor() {
        return new MyHandlerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/show/**").addResourceLocations("file:"+routeConfig.getHardDisk()+ File.separator);
        super.addResourceHandlers(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

}

class MyHandlerInterceptor extends HandlerInterceptorAdapter {


    @Resource
    private RouteConfig routeConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = WebUtil.getIpAddress(request);
        String path = request.getServletPath();
        //不对匹配该值的访问路径拦截（正则）
        final String NO_INTERCEPTOR_PATH = ".*/((show)).*";
        if(path.matches(NO_INTERCEPTOR_PATH)){ //允许展示路径
            return true;
        }else{
            //允许ip可以进行上传访问
            if(Arrays.asList(routeConfig.getIPs()).contains(ip)){
                return true;
            }else {
                return false;
            }
        }
    }



}